package org.giovanolli.mumi.export;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.List;

import org.giovanolli.mumi.entities.Bill;
import org.giovanolli.mumi.entities.BillDetail;
import org.giovanolli.mumi.entities.Patient;
import org.giovanolli.mumi.util.DateUtils;
import org.giovanolli.mumi.util.NumberUtils;
import org.giovanolli.mumi.view.util.FacesContextUtils;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.Table;

/**
 * The Class BillTemplate.
 */
public class BillTemplate extends AbstractTemplate<Bill> {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.giovanolli.mumi.export.AbstractTemplate#applyContent(com.lowagie.text.Document, org.giovanolli.mumi.entities.IdentificableEntity)
	 */
	@Override
	protected void applyContent(Document document, Bill bill) throws BadElementException, MalformedURLException, DocumentException, IOException {
		document.add(generateHeader(bill.getDate(), bill.getBillId().getId()));
		document.add(generatePatientData(bill.getPatient()));
		document.add(generateBillDetailData(bill.getBillDetails()));
		document.add(generateBillDetailTotalData(bill.getAmount()));
		document.add(generateFooter());
	}

	private final Table generateBillDetailData(List<BillDetail> billDetails) throws DocumentException {
		Table billDetailData = new Table(4);
		billDetailData.setWidth(100);
		billDetailData.setPadding(2f);

		// Generate detail Header
		Cell qtyHeaderCell = generateTableHeaderCell("Cantidad");
		qtyHeaderCell.setWidth(10);
		billDetailData.addCell(qtyHeaderCell);
		billDetailData.addCell(generateTableHeaderCell("Description"));
		billDetailData.addCell(generateTableHeaderCell("P.Unit."));
		billDetailData.addCell(generateTableHeaderCell("P.Total"));

		// generate detail content
		for (BillDetail billDetail : billDetails) {
			Cell qtyRowCell = generateTableRowCell(billDetail.getQuantity().toString());
			qtyRowCell.setWidth(10);
			billDetailData.addCell(qtyRowCell);
			billDetailData.addCell(generateTableRowCell(billDetail.getSpecialistFee().getDescription()));
			billDetailData.addCell(generateTableRowCell(NumberUtils.getCurrecyFormattedNumber(billDetail.getSpecialistFee().getAmount())));
			billDetailData.addCell(generateTableRowCell(NumberUtils.getCurrecyFormattedNumber(billDetail.getAmount())));
		}
		billDetailData.setWidths(new int[] { 12, 64, 12, 12 });
		return billDetailData;
	}

	private final Table generateBillDetailTotalData(Double amount) throws DocumentException {
		Table billDetailTotalData = new Table(4);
		billDetailTotalData.setWidth(100);
		billDetailTotalData.setPadding(2f);

		Cell totalLabel = getFormattedForHeaderCell();

		totalLabel.setColspan(3);
		totalLabel.setHorizontalAlignment("Right");
		totalLabel.add(new Chunk("TOTAL", FONT_TABLE_HEADER));
		billDetailTotalData.addCell(totalLabel);

		Cell totalAmount = getFormattedForHeaderCell();
		totalAmount.add(new Chunk(NumberUtils.getCurrecyFormattedNumber(amount), FONT_TABLE_HEADER));
		billDetailTotalData.addCell(totalAmount);

		billDetailTotalData.setWidths(new int[] { 20, 20, 48, 12 });
		return billDetailTotalData;
	}

	private final Table generateFooter() throws BadElementException {
		Table billFooter = new Table(1);
		billFooter.setWidth(100);
		billFooter.setPadding(2f);
		billFooter.setBottom(400);
		Cell content = generateTableHeaderCell("DOCUMENTO NO VALIDO COMO FACTURA");
		billFooter.addCell(content);
		return billFooter;
	}

	/**
	 * Generate header.
	 * 
	 * @return the table
	 * @throws BadElementException
	 *             the bad element exception
	 * @throws MalformedURLException
	 *             the malformed url exception
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	private final Table generateHeader(Date date, Integer id) throws BadElementException, MalformedURLException, IOException {
		Table header = new Table(2);
		header.setWidth(100);
		header.setPadding(2f);

		// Logo cell
		Cell logoCell = getFormattedForHeaderCell();
		String logoPath = FacesContextUtils.getRealPath() + File.separator + "resources" + File.separator + "images" + File.separator + "logo_90_45.png";
		logoCell.add(Image.getInstance(logoPath));
		logoCell.add(new Chunk("Centro de Atencion Integral"));
		header.addCell(logoCell);

		// Title cell
		Cell titleCell = getFormattedForHeaderCell();
		titleCell.add(new Chunk("COMPROBANTE DE PAGO", FONT_TABLE_HEADER));
		titleCell.add(Chunk.NEWLINE);
		titleCell.add(this.generateKeyValueChunk("Numero", String.format("%08d", id)));
		titleCell.add(Chunk.NEWLINE);
		titleCell.add(this.generateKeyValueChunk("Fecha", DateUtils.getSimpleFormattedDate(date)));
		header.addCell(titleCell);
		return header;
	}

	/**
	 * Generate patient data.
	 * 
	 * @return the table
	 * @throws BadElementException
	 *             the bad element exception
	 */
	private final Table generatePatientData(Patient patient) throws BadElementException {
		Table patientData = new Table(1);
		patientData.setWidth(100);
		patientData.setPadding(2f);

		// name cell
		Cell nameCell = new Cell();
		nameCell.setVerticalAlignment("Center");
		nameCell.setHorizontalAlignment("Left");
		nameCell.add(generateKeyValueChunk("Nombre", patient.getFullName()));
		nameCell.add(Chunk.NEWLINE);
		nameCell.add(generateKeyValueChunk("Documento No.", patient.getDocumentNumber()));
		patientData.addCell(nameCell);

		return patientData;
	}
}
